const WebSocket = require('ws');

const server = new WebSocket.Server({ port: 8888, host: "0.0.0.0" });
const userList = [];

server.on('connection', (socket) => {
  console.log('server connection success.');
  console.log('socket:', socket._socket.remoteAddress);

  socket.on('message', (message) => {
    console.log('message:', message);
    // 广播消息给所有连接的客户端
    server.clients.forEach((client) => {
      if (client !== socket && client.readyState === WebSocket.OPEN) {
        const content = JSON.parse(message.toString('utf8'))
        console.log('content =>', content);
        if (content.type === 0) {
          const data = { ...content, ip: socket._socket.remoteAddress }
          client.send(JSON.stringify(data))
        } else if (content.type === 1) {
          const data = { ...content }
          client.send(JSON.stringify(data));
        }
      }
    });
  });
});
server.on('close', () => {
  console.log('server close.');
})

console.log('服务器正在运行在 ws://192.168.5.78:8888');